<template>
  <div>
    <!-- 面包屑-->
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <el-card>
      <el-row>
        <el-col>
          <el-button type='primary' @click='addCatePull'>添加分类</el-button>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <tree-table :data='cateList'
                    :columns='columns'
                    :selection-type='false'
                    :expand-type='false'
                    :show-row-hover='false'
                    show-index index-text='#'
                    border>
          <!-- 是否有效 -->
          <template slot='iscate' slot-scope='scope'>
            <i class='el-icon-success' v-if='scope.row.cat_deleted===false'></i>
            <i class='el-icon-error' v-else></i>
          </template>
          <!-- 排序 -->
          <template slot='order' slot-scope='scope'>
            <el-tag size='mini' v-if='scope.row.cat_level===0'>一级</el-tag>
            <el-tag size='mini' type='success' v-if='scope.row.cat_level===1'>二级</el-tag>
            <el-tag size='mini' type='warning' v-if='scope.row.cat_level===2'>三级</el-tag>
          </template>
          <!-- 操作 -->
          <template slot='under' slot-scope='scope'>
            <el-button type='primary' size='mini' icon='el-icon-edit' @click='updateCatePull(scope.row)'>编辑</el-button>
            <el-button type='danger' size='mini' icon='el-icon-delete' @click='delCatePull(scope.row)'>删除</el-button>
          </template>
        </tree-table>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <!-- 分页模块 -->
        <el-pagination
          @size-change='handleSizeChange'
          @current-change='handleCurrentChange'
          :current-page.sync='queryInfo.pagenum'
          :page-size='queryInfo.pagesize'
          :page-sizes='[3,5,10,10,20]'
          background
          layout='total,sizes, prev, pager, next,jumper'
          :total='this.total'>
        </el-pagination>
      </el-row>
      <!-- 添加分类弹出框 -->
      <el-dialog
        title='添加分类'
        :visible.sync='addCateVisible'
        width='40%' @close='closeAddCate'>
        <el-form ref='addCateRef' :model='addCateForm' :rules='addCateRule' label-width='100px'>
          <el-form-item label='分类名称' prop='cat_name'>
            <el-input v-model='addCateForm.cat_name'></el-input>
          </el-form-item>
          <el-form-item label='父级分类'>
            <el-cascader
              v-model='cascaderCateId'
              :options='cateParentList'
              :props='cascaderOption'
              placeholder="不选,默认为一级分类"
              clearable
              @change='cascaderCateChange'></el-cascader>
          </el-form-item>
        </el-form>
        <span slot='footer' class='dialog-footer'>
    <el-button @click='addCateVisible = false'>取 消</el-button>
    <el-button type='primary' @click='addCate'>添 加</el-button>
  </span>
      </el-dialog>

      <!-- 编辑分类弹出框 -->
      <el-dialog
        title='修改分类'
        :visible.sync='updateCateVisible'
        width='50%'>
        <el-form ref='updateCateRef' :model='updateCateForm' :rules='updateCateRule' label-width='100px'>
          <el-form-item label='分类名称' prop='cat_name'>
            <el-input v-model='updateCateForm.cat_name'></el-input>
          </el-form-item>
        </el-form>
        <span slot='footer' class='dialog-footer'>
    <el-button @click='updateCateVisible = false'>取 消</el-button>
    <el-button type='primary' @click='updateCate'>修 改</el-button>
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'GoodsCate',
  data() {
    return {
      // 所有商品分类
      cateList: [],
      // 请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 数据总条数
      total: 0,
      // table中每一列
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          align: 'center',
          headerAlign: 'center'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'iscate',
          align: 'center',
          headerAlign: 'center'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
          align: 'center',
          headerAlign: 'center'
        },
        {
          label: '操作',
          type: 'template',
          template: 'under',
          align: 'center',
          headerAlign: 'center'
        }],
      // 添加分类显示框
      addCateVisible: false,
      // 分类名称
      addCateForm: {
        cat_name: '',
        cat_pid: 0, // 父级分类ID
        cat_level: 0 // 父级层次
      },
      // 添加分类的验证规则
      addCateRule: {
        cat_name: [
          { required: true, message: '分类名称必填', trigger: 'blur' }
        ]
      },
      // 父级分类的列表
      cateParentList: [],
      // 级联选择器的配置项
      cascaderOption: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        // 选择任意一个层级
        checkStrictly: true
      },
      // 级联选择器的数据双向绑定
      cascaderCateId: [],

      // 控制显示编辑分类弹出框
      updateCateVisible: false,
      // 编辑分类model绑定
      updateCateForm: {
        cat_name: '',
        cat_id: ''
      },
      // 编辑分类的效验规则
      updateCateRule: {
        cat_name: [
          { required: true, message: '分类名称必填', trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$msg.error('获取商品分类失败')
      }
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    // 点击添加分类拉起显示框
    addCatePull() {
      this.getCateParentList()
      this.addCateVisible = true
    },
    // 获取级联选择器中父级列表
    async getCateParentList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) {
        return this.$msg.error('获取父级列表失败')
      }
      this.cateParentList = res.data
    },
    // 级联选择器选择触发
    cascaderCateChange() {
      if (this.cascaderCateId.length > 0) {
        this.addCateForm.cat_pid = this.cascaderCateId[this.cascaderCateId.length - 1]
        this.addCateForm.cat_level = this.cascaderCateId.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 添加分类
    addCate() {
      this.$refs.addCateRef.validate(async valid => {
        if (!valid) {
          return this.$msg.warning('分类名称不能为空')
        }
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        if (res.meta.status !== 201) {
          return this.$msg.error('添加分类失败')
        }
        this.$msg.success('添加分类成功')
        await this.getCateList()
        this.addCateVisible = false
      })
    },
    // 关闭添加分类框时清除表单数据
    closeAddCate() {
      this.$refs.addCateRef.resetFields()
      this.cascaderCateId = []
    },
    // 拉起编辑分类弹出框
    async updateCatePull(data) {
      const { data: res } = await this.$http.get('categories/' + data.cat_id)
      if (res.meta.status !== 200) {
        return this.$msg.error('没有查询到该分类')
      }
      this.updateCateForm.cat_name = res.data.cat_name
      this.updateCateForm.cat_id = res.data.cat_id
      this.updateCateVisible = true
    },
    // 更新分类名称
    updateCate() {
      this.$refs.updateCateRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('categories/' + this.updateCateForm.cat_id, { cat_name: this.updateCateForm.cat_name })
        if (res.meta.status !== 200) {
          return this.$msg.error('更新分类失败')
        }
        this.$msg.success('更新分类成功')
        await this.getCateList()
        this.updateCateVisible = false
      })
    },
    // 拉起删除分类弹出框
    async delCatePull(data) {
      const result = await this.$confirm('确定删除该分类?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).catch(err => err)
      if (result !== 'confirm') return
      const { data: res } = await this.$http.delete('categories/' + data.cat_id)
      if (res.meta.status !== 200) {
        return this.$msg.error('删除分类失败')
      }
      this.$msg.success('删除分类成功')
      await this.getCateList()
    }
  }
}
</script>

<style lang='less' scoped>
.el-icon-success {
  color: #008000;
}

.el-icon-error {
  color: #9c0000;
}

.el-pagination {
  text-align: center;
}

.el-cascader {
  width: 100%;
}

</style>
